<?php
class ShopLogic extends CommonModel
{
	CONST USER_SHOPS = 'USER_SHOPS:';
	
	// 缓存模型类
	private $_CacheModel = '';
	
	public function __construct() {
		$this -> _CacheModel = D('Cache', 'Service');
		$this -> _CacheModel -> init();
	}
	
	/**
	 * 获取商铺类型
	 * @return array
	 */
	public function getShopTypes() {
		return ShopModel::$shopTypes;
	}
	
	/**
	 * 获取开店需要消费的积分
	 */
	public function getOpenShopCost($code) {
		if (!$code)
			return -1;
	
		$mark = '';
		switch ($code) {
			case 10001:
				$mark = 'car_4s_shop_cost';
				break;
			case 10002:
				$mark = 'car_old_shop_cost';
				break;
			case 10003:
				$mark = 'car_rent_shop_cost';
				break;
			case 10004:
				$mark = 'shoe_cloth_shop_cost';
				break;
			case 10005:
				$mark = 'food_drink_shop_cost';
				break;
			case 10006:
				$mark = 'groceries_shop_cost';
				break;
			case 10007:
				$mark = 'secondary_market_cost';
				break;
			default:
				$mark = 'other_shop_cost';
		}
	
		$config = D('Setting', 'Logic') -> getConfigList();
		if (!isset($config[$mark]))
			return -1;
	
		return $config[$mark]['value'];
	}
	
	/**
	 * 获取用户的商铺信息
	 */
	public function getUserShops($uId) {
		$key = self::USER_SHOPS . $uId;
		
		$shops = $this -> _CacheModel -> get($key);

		if (!$shops) {
			$sql = 'customer_id = ' . $uId;
			$tempShops = M('Shop') -> field('*') -> where($sql) -> select();
			
			$shops = array();
			if (is_array($tempShops) && !empty($tempShops)) {
				foreach($tempShops as $val) {
					$shops[$val['id']] = $val;
				}
			}
				
			$this -> _CacheModel -> set($key, $shops);
			$this -> _CacheModel -> saveKeys($key, 'user', $uId);
		}
	
		return $shops;
	}
	
	/**
	 * 获取店铺信息
	 * @param integer $id
	 * @param integer $uId
	 */
	public function getShopInfo($id, $uId) {
		$shops = $this -> getUserShops($uId);
		
		$shopInfo = array();
		if (isset($shops[$id])) 
			$shopInfo = $shops[$id];
		
		return $shopInfo;
	}
	
	/**
	 * 开设店铺
	 */
	public function addShop() {
		$uId = $this -> getUid();
		$key = self::USER_SHOPS . $uId;
		$Model = D('Shop');
		$ret = $Model -> create();
		if (!$ret) {
			$this -> error = $Model -> getError();
			return 0;
		}
	
		$Model -> customer_id = $uId;
		$Model -> create_time = time();
		
		$ret = $Model -> add();
		if ($ret)
			$this -> _CacheModel -> rm($key);
		else
			$this -> error = '添加店铺信息失败！';
			
		return $ret;
	}
	
}